<template>
  <view class="clicks-container">
    <!-- 标题栏 -->
    <view class="header">
      <text class="title">浏览历史</text>
      <view class="header-right">
        <view class="sort-options">
          <text 
            class="sort-item" 
            :class="{ active: sortType === 'time' }"
            @click="changeSortType('time')"
          >
            时间
          </text>
          <text 
            class="sort-item" 
            :class="{ active: sortType === 'count' }"
            @click="changeSortType('count')"
          >
            次数
          </text>
        </view>
        <text class="count">共{{ total }}个</text>
      </view>
    </view>

    <!-- 点击历史列表 -->
    <view class="clicks-list" v-if="clickList.length > 0">
      <view 
        class="click-item" 
        v-for="item in clickList" 
        :key="item.id"
        @click="viewDishDetail(item.dishId)"
      >
        <image :src="item.dishImage || '/static/images/default-dish.jpg'" class="dish-image" mode="aspectFill" />
        <view class="dish-info">
          <text class="dish-name">{{ item.dishName || '菜品' + item.dishId }}</text>
          <view class="dish-tags" v-if="item.cuisine || item.taste">
            <text class="tag cuisine" v-if="item.cuisine">{{ item.cuisine }}</text>
            <text class="tag taste" v-if="item.taste">{{ item.taste }}</text>
          </view>
          <view class="nutrition-info" v-if="item.calories || item.protein">
            <text class="nutrition-item" v-if="item.calories">🔥 {{ item.calories }}千卡</text>
            <text class="nutrition-item" v-if="item.protein">🥩 {{ item.protein }}g蛋白质</text>
          </view>
          <text class="click-time">浏览时间: {{ formatTime(item.createTime) }}</text>
          <view class="click-stats">
            <text class="click-count" :class="getCountClass(item.count)">
              浏览次数: {{ item.count || 1 }}次
            </text>
            <text class="hot-tag" v-if="item.count >= 5">🔥 热门</text>
          </view>
        </view>
        <view class="actions">
          <button class="detail-btn" @click.stop="viewDishDetail(item.dishId)">
            查看详情
          </button>
        </view>
      </view>
    </view>

    <!-- 空状态 -->
    <view class="empty-state" v-else>
      <text class="empty-text">暂无浏览记录</text>
      <button class="goto-recommend" @click="gotoRecommend">
        去推荐页面看看
      </button>
    </view>

    <!-- 加载更多 -->
    <uni-load-more :status="loadStatus" v-if="clickList.length > 0" />
  </view>
</template>

<script>
import { getUserClickList } from '@/api/diet'

export default {
  data() {
    return {
      clickList: [],
      total: 0,
      pageNum: 1,
      pageSize: 10,
      loadStatus: 'more',
      sortType: 'time' // time: 按时间排序, count: 按次数排序
    }
  },
  onLoad() {
    this.loadClickList()
  },
  onReachBottom() {
    if (this.loadStatus === 'more') {
      this.loadMore()
    }
  },
  methods: {
    async loadClickList() {
      try {
        this.loadStatus = 'loading'
        const userId = this.getUserId()
        
        const res = await getUserClickList(userId, this.pageNum, this.pageSize)
        
        if (res.code === 200) {
          const processedData = (res.rows || []).map(item => {
            console.log('📊 处理点击数据:', item)
            return {
              id: item.id,
              dishId: item.dishId,
              dishName: item.dishName || '菜品' + item.dishId,
              dishImage: item.imgUrl ? `http://localhost:8080${item.imgUrl}` : '/static/images/default-dish.jpg',
              createTime: item.createTime,
              count: item.count || 1,
              cuisine: item.cuisine || '未知',
              taste: item.taste || '未知',
              calories: item.calories || 0,
              protein: item.protein || 0
            }
          })
          
          if (this.pageNum === 1) {
            this.clickList = processedData
          } else {
            this.clickList = [...this.clickList, ...processedData]
          }
          
          // 按排序类型排序
          this.sortClickList()
          this.total = res.total || 0
          
          if (res.rows && res.rows.length < this.pageSize) {
            this.loadStatus = 'noMore'
          } else {
            this.loadStatus = 'more'
          }
        } else {
          this.loadStatus = 'more'
          uni.showToast({ title: '加载失败', icon: 'none' })
        }
      } catch (error) {
        this.loadStatus = 'more'
        uni.showToast({ title: '加载失败', icon: 'none' })
      }
    },
    
    loadMore() {
      this.pageNum++
      this.loadClickList()
    },
    
    getUserId() {
      let userId = uni.getStorageSync('userId')
      if (!userId) {
        userId = 100
        uni.setStorageSync('userId', userId)
      }
      return Number(userId)
    },
    
    formatTime(timeStr) {
      if (!timeStr) return ''
      const date = new Date(timeStr)
      return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`
    },
    
    viewDishDetail(dishId) {
      uni.navigateTo({
        url: `/pages/diet/detail/index?id=${dishId}`
      })
    },
    
    gotoRecommend() {
      uni.switchTab({
        url: '/pages/diet/recommend/index'
      })
    },
    
    changeSortType(type) {
      this.sortType = type
      this.sortClickList()
    },
    
    sortClickList() {
      if (this.sortType === 'count') {
        // 按点击次数降序排序
        this.clickList.sort((a, b) => (b.count || 1) - (a.count || 1))
      } else {
        // 按时间降序排序（最新的在前）
        this.clickList.sort((a, b) => new Date(b.createTime) - new Date(a.createTime))
      }
    },
    
    getCountClass(count) {
      const num = count || 1
      if (num >= 10) return 'very-high'
      if (num >= 5) return 'high'
      if (num >= 3) return 'medium'
      return 'normal'
    }
  }
}
</script>

<style lang="scss" scoped>
.clicks-container {
  padding: 20rpx;
  background-color: #f5f5f5;
  min-height: 100vh;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30rpx;
  padding: 20rpx;
  background: white;
  border-radius: 16rpx;
}

.header-right {
  display: flex;
  align-items: center;
}

.sort-options {
  display: flex;
  margin-right: 20rpx;
}

.sort-item {
  font-size: 24rpx;
  color: #666;
  padding: 8rpx 16rpx;
  border-radius: 12rpx;
  margin-right: 10rpx;
  
  &.active {
    background: #1890ff;
    color: white;
  }
}

.title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
}

.count {
  font-size: 24rpx;
  color: #666;
}

.click-item {
  display: flex;
  align-items: center;
  background: white;
  border-radius: 16rpx;
  padding: 20rpx;
  margin-bottom: 20rpx;
}

.dish-image {
  width: 120rpx;
  height: 120rpx;
  border-radius: 12rpx;
  margin-right: 20rpx;
}

.dish-info {
  flex: 1;
}

.dish-name {
  font-size: 28rpx;
  font-weight: bold;
  color: #333;
  display: block;
  margin-bottom: 10rpx;
}

.dish-tags {
  display: flex;
  margin-bottom: 8rpx;
}

.tag {
  font-size: 20rpx;
  padding: 4rpx 8rpx;
  border-radius: 8rpx;
  margin-right: 8rpx;
  
  &.cuisine {
    background: #e6f7ff;
    color: #1890ff;
  }
  
  &.taste {
    background: #f6ffed;
    color: #52c41a;
  }
}

.nutrition-info {
  display: flex;
  margin-bottom: 8rpx;
}

.nutrition-item {
  font-size: 20rpx;
  background: #f0f9ff;
  color: #0369a1;
  padding: 4rpx 8rpx;
  border-radius: 8rpx;
  margin-right: 8rpx;
}

.click-time {
  font-size: 24rpx;
  color: #999;
  display: block;
  margin-bottom: 5rpx;
}

.click-stats {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.click-count {
  font-size: 24rpx;
  font-weight: bold;
  
  &.normal {
    color: #999;
  }
  
  &.medium {
    color: #1890ff;
  }
  
  &.high {
    color: #ff4d4f;
  }
  
  &.very-high {
    color: #722ed1;
  }
}

.hot-tag {
  font-size: 20rpx;
  background: linear-gradient(45deg, #ff6b6b, #ffa500);
  color: white;
  padding: 4rpx 8rpx;
  border-radius: 8rpx;
  margin-left: 10rpx;
}

.detail-btn {
  background: #1890ff;
  color: white;
  border: none;
  border-radius: 20rpx;
  padding: 10rpx 20rpx;
  font-size: 24rpx;
}

.empty-state {
  text-align: center;
  padding: 100rpx 0;
}

.empty-text {
  font-size: 28rpx;
  color: #999;
  display: block;
  margin-bottom: 40rpx;
}

.goto-recommend {
  background: #1890ff;
  color: white;
  border: none;
  border-radius: 30rpx;
  padding: 20rpx 40rpx;
  font-size: 28rpx;
}
</style>